<?php
namespace app\model\lawcase;

use think\Model;

/**
 * 当事人模型
 * 用于存储和管理案件当事人的基本信息
 */
class Party extends Model
{
    // 设置表名（不包含前缀）
    protected $name = 'party';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dateFormat = 'Y-m-d H:i:s';
    
    /**
     * 构造函数
     * @param array $data 初始化数据
     */
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }
    
    /**
     * 类型转换
     */
    protected $type = [
        'id_number' => 'string',
        'contact' => 'string',
        'phone' => 'string',
        'party_type' => 'integer',
        'party_source' => 'integer',
        'contract_id' => 'integer',
        'contact_id' => 'integer',
        'create_time' => 'timestamp',
        'update_time' => 'timestamp',
        'delete_time' => 'timestamp'
    ];
    
    /**
     * 根据ID获取当事人信息
     * @param int $id 当事人ID
     * @param array $field 字段列表
     * @return array|null 当事人信息
     */
    public static function getPartyById(int $id, array $field = ['*']) {
        return self::field($field)
            ->where(['id' => $id, 'delete_time' => 0])
            ->findOrEmpty()
            ->toArray();
    }
    
    /**
     * 根据IDs批量获取当事人信息
     * @param array $ids 当事人ID列表
     * @param array $field 字段列表
     * @return array 当事人信息列表
     */
    public static function getPartiesByIds(array $ids, array $field = ['*']) {
        if (empty($ids)) {
            return [];
        }
        
        $parties = self::field($field)
            ->where('id', 'in', $ids)
            ->where(['delete_time' => 0])
            ->select()
            ->toArray();
            
        // 按ID索引，方便快速查找
        $result = [];
        foreach ($parties as $party) {
            $result[$party['id']] = $party;
        }
        
        return $result;
    }
    
    /**
     * 根据名称搜索当事人
     * @param string $name 当事人名称
     * @return array 当事人列表
     */
    public static function searchPartiesByName(string $name) {
        return self::where('name', 'like', '%' . $name . '%')
            ->where(['delete_time' => 0])
            ->limit(20)
            ->select()
            ->toArray();
    }
    
    /**
     * 获取当事人类型文本
     * @param int $type 类型ID
     * @return string 类型文本
     */
    public static function getPartyTypeText(int $type) {
        $types = [
            0 => '未知',
            1 => '自然人',
            2 => '法人',
            3 => '其他组织'
        ];
        return $types[$type] ?? '未知';
    }
    
    /**
     * 获取当事人来源文本
     * @param int $source 来源ID
     * @return string 来源文本
     */
    public static function getPartySourceText(int $source) {
        $sources = [
            1 => '客户本身',
            2 => '客户联系人',
            3 => '外部人员'
        ];
        return $sources[$source] ?? '未知';
    }
    
    /**
     * 添加新当事人
     * @param array $data 当事人数据
     * @return int|false 新增ID或false
     */
    public static function addParty(array $data) {
        $now = time();
        $partyData = [
            'name' => $data['name'],
            'party_type' => $data['party_type'] ?? 0,
            'party_source' => $data['party_source'] ?? 1,
            'contract_id' => $data['contract_id'] ?? 0,
            'contact_id' => $data['contact_id'] ?? 0,
            'id_number' => $data['id_number'] ?? '',
            'contact' => $data['contact'] ?? '',
            'phone' => $data['phone'] ?? '',
            'create_time' => $now,
            'update_time' => $now,
            'delete_time' => 0
        ];
        
        $party = new self($partyData);
        return $party->save() ? $party->getData('id') : false;
    }
    
    /**
     * 更新当事人信息
     * @param int $id 当事人ID
     * @param array $data 更新数据
     * @return bool 更新结果
     */
    public static function updateParty(int $id, array $data) {
        return self::where(['id' => $id, 'delete_time' => 0])
            ->update(array_merge($data, ['update_time' => time()])) !== false;
    }
    
    /**
     * 根据客户ID检查当事人是否存在
     * @param int $customerId 客户ID
     * @return array|null 当事人信息或null
     */
    public static function getPartyByCustomerId(int $customerId): ?array
    {
        return self::where(['customer_id' => $customerId, 'delete_time' => 0])
            ->findOrEmpty()
            ->toArray();
    }
    
    /**
     * 从客户创建当事人
     * @param array $customerData 客户数据
     * @return int|false 新当事人ID或false
     */
    public static function createPartyFromCustomer(array $customerData)
    {
        $now = time();
        $partyData = [
            'customer_id' => $customerData['id'],
            'name' => $customerData['name'],
            'party_type' => 1, // 默认类型为自然人
            'party_source' => 1, // 来源为客户本身
            'id_number' => '',
            'contact' => '',
            'phone' => '',
            'create_time' => $now,
            'update_time' => $now,
            'delete_time' => 0
        ];
        
        $party = new self($partyData);
        return $party->save() ? $party->getData('id') : false;
    }
}